from config.database import async_engine, AsyncSessionLocal, Base
from utils.log_util import logger


async def get_db():
    """
    每一个请求完毕后关闭数据库连接 不同的请求不同的连接
    :return:
    """

    async with AsyncSessionLocal() as current_db:
        try:
            yield current_db
        except Exception as e:
            logger.error(e)
            current_db.rollback()
        finally:
            current_db.close()


async def init_create_table():
    """
    启动初始化数据库连接
    :return:
    """
    logger.info('初始化数据库连接')
    async with async_engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)
    logger.info('初始化数据库连接成功')
